var Consts = require('../../../util/consts');
var RoomRemote = require('../remote/roomRemote');

module.exports = function (app) {
    return new RoomHandler(app);
};


var RoomHandler = function (app) {
    this.app = app;
    this.roomRemote = new RoomRemote(app);
};
var handler = RoomHandler.prototype;

/**
 *
 * @param msg {username:xxx}
 * @param session
 * @param next
 */
handler.whoami = function (msg, session, next) {
    var rid = session.get('rid');

    console.log(rid);
    var username = msg.username;

    this.roomRemote.whoami(username, rid, function (err, room) {
        console.log('get room: ' + err);
        console.log('room: ' + room);
        if (room && room['master'] == username) {
            next(null, {code: Consts.code.SUCCESS, role: Consts.role.HIDER,
                userAmount: room['userList'].length,
                users: room['userList']});
        } else if (room) {
            next(null, {code: Consts.code.SUCCESS, role: Consts.role.SEEKER,
                userAmount: room['userList'].length});
        } else {
            next(null, {code: 400, msg: "room does not exist"});
        }
    });


};

// TODO: Argar platform migration -- using new chat room!
handler.createRoom = function (msg, session, next) {

    var rid = msg.rid;
    var usernames = msg.usernames || "[]";
    var master = msg.master;

    var game = msg.game || 'hideAndSeek';


    this.roomRemote.createRoom(master, rid, usernames, function (err, room) {
        if (room) {
            console.log("create room success");

            next(null, {code: Consts.code.SUCCESS});
        } else {
            next(null, {code: Consts.code.FAIL});
        }
    });


};